package com.fansl.koala.quickdev.module.users.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fansl.koala.quickdev.common.bean.PageBean;
import com.fansl.koala.quickdev.common.bean.R;
import com.fansl.koala.quickdev.common.constants.CommonConstants;
import com.fansl.koala.quickdev.common.enums.DeleteFlagEnum;
import com.fansl.koala.quickdev.common.enums.ResultEnum;
import com.fansl.koala.quickdev.common.enums.StatusEnum;
import com.fansl.koala.quickdev.common.exception.BizException;
import com.fansl.koala.quickdev.module.users.bean.dto.SysRoleDTO;
import com.fansl.koala.quickdev.module.users.entity.SysRole;
import com.fansl.koala.quickdev.module.users.service.ISysRoleService;
import com.fansl.koala.quickdev.module.users.vo.SysRoleVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色表 前端控制器
 * </p>
 *
 * @author fansl
 * @since 2020-03-22
 */
@RestController
@AllArgsConstructor
@RequestMapping("/users/sys-role")
public class SysRoleController {
    private final ISysRoleService sysRoleService;

    /**
     * 添加
     *
     * @param sysRoleDTO 参数
     * @return true/false
     */
    @PostMapping("")
    public Mono<R<Boolean>> add(@RequestBody SysRoleDTO sysRoleDTO) {
        // 查询是否存在
        SysRole queryRole = sysRoleService.getByCode(sysRoleDTO.getRoleCode());
        if (queryRole != null) {
            throw new BizException(ResultEnum.ROLE_EXIST);
        }
        SysRole sysRole = sysRoleDTO2Bean(sysRoleDTO);
        sysRole.setRoleId(null);
        boolean b = sysRoleService.save(sysRole);
        return Mono.just(R.ok(b));
    }

    /**
     * 根据主键更新
     *
     * @param sysRoleDTO 参数
     * @return true/false
     */
    @PutMapping("")
    public Mono<R<Boolean>> updateById(@RequestBody SysRoleDTO sysRoleDTO) {
        SysRole sysRole = sysRoleDTO2Bean(sysRoleDTO);
        boolean b = sysRoleService.updateById(sysRole);
        return Mono.just(R.ok(b));
    }

    /**
     * 根据主键获取信息
     *
     * @param id 主键
     * @return 查询数据
     */
    @GetMapping("/{id}")
    public Mono<R<SysRoleVo>> getById(@PathVariable Long id) {
        SysRole sysRole = sysRoleService.getById(id);
        SysRoleVo sysRoleVo = sysRole2Vo(sysRole);
        return Mono.just(R.ok(sysRoleVo));
    }

    /**
     * 根据主键删除
     *
     * @param id 主键
     * @return true/false
     */
    @DeleteMapping("/{id}")
    public Mono<R<Boolean>> delById(@PathVariable Long id) {
        boolean b = sysRoleService.deleteById(id);
        return Mono.just(R.ok(b));
    }

    /**
     * 分页查询
     *
     * @param page    分页询参数
     * @param sysRole 查询参数
     * @return 查询数据
     */
    @GetMapping("/page")
    public Mono<R<PageBean<SysRoleVo>>> page(PageBean<SysRoleVo> page, SysRole sysRole) {
        //分页参数
        Page<SysRole> queryPage = new Page<>();
        queryPage.setCurrent(page.getPageNo());
        queryPage.setSize(page.getPageSize());
        if (StrUtil.isNotBlank(page.getSortOrder()) && StrUtil.isNotBlank(page.getSortField())) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(page.getSortOrder().equals(CommonConstants.PAGE_QUERY_ORDER_ASC));
            orderItem.setColumn(StrUtil.toUnderlineCase(page.getSortField()));
            queryPage.setOrders(Collections.singletonList(orderItem));
        }
        //查询
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(sysRole);
        Page<SysRole> result = sysRoleService.page(queryPage, queryWrapper);
        //结果转vo
        List<SysRoleVo> data = result.getRecords().stream()
                .map(this::sysRole2Vo)
                .collect(Collectors.toList());
        //转换结果
        page.setData(data);
        page.setTotalCount(result.getTotal());
        page.setTotalPage(result.getPages());
        return Mono.just(R.ok(page));
    }

    @GetMapping("/list")
    public Mono<R<List<SysRoleVo>>> list() {
        SysRole query = new SysRole();
        query.setDelFlag(DeleteFlagEnum.NOT_DELETE.getCode());
        List<SysRole> sysRoles = sysRoleService.list(Wrappers.lambdaQuery(query));
        List<SysRoleVo> sysRoleVos = sysRoles.stream().map(this::sysRole2Vo)
                .collect(Collectors.toList());
        return Mono.just(R.ok(sysRoleVos));
    }

    /**
     * Vo对象转换
     *
     * @param sysRole 源对象
     * @return 目标对象
     */
    private SysRoleVo sysRole2Vo(SysRole sysRole) {
        SysRoleVo target = new SysRoleVo();
        BeanUtil.copyProperties(sysRole, target, CopyOptions.create().setIgnoreError(true));
        target.setStatus(StatusEnum.findByCode(sysRole.getStatus()));
        return target;
    }

    /**
     * Po对象转换
     *
     * @param sysRoleDTO 源对象
     * @return 目标对象
     */
    private SysRole sysRoleDTO2Bean(SysRoleDTO sysRoleDTO) {
        SysRole target = new SysRole();
        BeanUtil.copyProperties(sysRoleDTO, target, CopyOptions.create().setIgnoreError(true));
        target.setStatus(sysRoleDTO.getStatus().getCode());
        return target;
    }
}
